package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 套餐服务实现类
 */

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;//从属性文件中读取要生成的html对应的目录

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 新增套餐
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {

        setmealDao.add(setmeal);

        //设置套餐和检查组的对应关系（勾选的情况）
        if(checkgroupIds != null && checkgroupIds.length > 0){

            setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        }

        //将图片名称存入redis (小)
        Jedis resource = jedisPool.getResource();
        resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());

        resource.close();
        //添加套餐成功后需要重新生成静态页面
        generateMobileStaticHtml();
    }


    //生成当前方法所需的静态页面（套餐，检查组，检查项）
    public void generateMobileStaticHtml(){
        //在生成静态页面之前查询数据
        List<Setmeal> list = setmealDao.findAll();

        //套餐列表页面生成
        generateMobileSetmealListHtml(list);

        //套餐详情页面生成
        generateMobileSetmealDetailHtml(list);
    }


    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();

        //生成静态页面
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);


    }

    //生成套餐详情静态页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }

    //通用生成静态页面方法
    public void generteHtml(String templateName,String htmlPageName,Map map){
        //获得配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();

        Writer out = null;

        try{
            Template template = configuration.getTemplate(templateName);

            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));

            //输出文件
            template.process(map,out);

            out.close();
        }catch (Exception e){

            e.printStackTrace();
        }
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //分页助手
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.selectByCondition(queryString);

        //封装pageResult
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 获取所有套餐信息
     * @return
     */
    @Override
    public List<Setmeal> findAll() {

        return setmealDao.findAll();

    }

    /**
     * 根据id查询套餐信息（包括检查组和检查项信息）
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    /**
     * 根据套餐id查询其对应的检查组
     * @param id
     * @return
     */
    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer id) {
        List<Integer> Ids = setmealDao.findCheckGroupIdsBySetmealId(id);
        return Ids;
    }

    /**
     * 编辑套餐
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //根据套餐id删除其对应的检查组约束关系
        setmealDao.deleteAssociation(setmeal.getId());
        //向中间表（t_setmeal_checkgroup)中插入约束关系
        setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);

        //根据套餐id获取图片img(未修改的)
        Setmeal byId = findById(setmeal.getId());

        String img = byId.getImg();

        //修改套餐数据
        setmealDao.edit(setmeal);

        //修改成功，删掉redis原先的img
        Jedis resource = jedisPool.getResource();
        resource.srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);

        //将修改后的图片添加到redis中
        resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        resource.close();



    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    /**
     * 设置套餐和检查组的对应约束关系
     * @param id
     * @param checkgroupIds
     */
    private void setSetmealAndCheckGroup(Integer id,Integer[] checkgroupIds){
        //遍历检查组，将套餐id和检查组id的对应关系封装成map
        for (Integer checkgroupId : checkgroupIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("setmeal_id",id);
            map.put("checkgroup_id",checkgroupId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }
}
